package fudan.se.project.service.infrastructure.entity.conference.production;

import fudan.se.project.domain.conference.Conference;
import fudan.se.project.domain.conference.production.ReviewCopy;
import fudan.se.project.domain.conference.production.ReviewInfo;
import fudan.se.project.repository.entity.conference.production.ReviewCopyRepository;
import fudan.se.project.repository.entity.conference.production.ReviewInfoRepository;
import fudan.se.project.service.infrastructure.base.IEntityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
@Service
public class ReviewCopyService implements IEntityService<ReviewCopy> {
    private final ReviewCopyRepository reviewCopyRepository;
    private final ReviewInfoRepository reviewInfoRepository;

    @Autowired
    public ReviewCopyService(ReviewCopyRepository reviewCopyRepository, ReviewInfoRepository reviewInfoRepository) {
        this.reviewCopyRepository = reviewCopyRepository;
        this.reviewInfoRepository = reviewInfoRepository;
    }

    public ReviewCopy findByReviewInfo(ReviewInfo reviewInfo) {
        return reviewCopyRepository.findByReviewInfo(reviewInfo);
    }

    public void substituteReviewInfos(Conference conference) {
        final List<ReviewCopy> reviewCopies = reviewCopyRepository.findDistinctByReviewInfoPaperConference(conference);
        ReviewInfo reviewInfo;
        ArrayList<ReviewInfo> reviewInfos = new ArrayList<>();
        for (ReviewCopy reviewCopy : reviewCopies) {
            reviewInfo = reviewCopy.getReviewInfo();
            reviewInfo.setComment(reviewCopy.getComment());
            reviewInfo.setReviewConfidence(reviewCopy.getReviewConfidence());
            reviewInfo.setReviewInfoState(reviewCopy.getReviewInfoState());
            reviewInfos.add(reviewInfo);
        }
        reviewInfoRepository.saveAll(reviewInfos);
    }

    @Override
    public ReviewCopy findById(long id) {
        return reviewCopyRepository.findById(id);
    }

    @Override
    public ReviewCopy save(ReviewCopy reviewCopy) {
        return reviewCopyRepository.save(reviewCopy);
    }

    @Override
    public Iterable<ReviewCopy> saveAll(Collection<ReviewCopy> reviewCopies) {
        return reviewCopyRepository.saveAll(reviewCopies);
    }
}
